<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <style>
      .parent {
        height: 450px;
        overflow: auto;
      }
      .box {
        width: 20px;
        height: 100px;
        border: 1px solid gray;
      }
      .active {
        background-color: aquamarine;
      }
    </style>
    <div class="parent">
      <div class="box">1</div>
      <div class="box">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
      <div class="box">5</div>
      <div class="box">6</div>
      <div class="box">7</div>
      <div class="box">8</div>
      <div class="box">9</div>
      <div class="box">10</div>
      <div class="box">11</div>
      <div class="box">12</div>
      <div class="box">13</div>
      <div class="box"></div>
    </div>
    <script>
      // 注册 IntersectionObserver
      const io = new IntersectionObserver((entries) => {
        console.log("🚀 ~ io ~ entries:", entries);

        entries.forEach((entry) => {
          if (entry.intersectionRatio > 0) {
            // 如果观察目标在视口内，则添加“active”类
            entry.target.classList.add("active");
          } else {
            // 否则移除“active”类
            entry.target.classList.remove("active");
          }
        });
      });

      // 声明观察的内容，并观察其属性。
      const boxElList = document.querySelectorAll(".box");
      boxElList.forEach((el) => {
        io.observe(el);
      });
    </script>
  </body>
</html>
